<template>
  <el-table 
    :data="tableData || []" 
    v-loading="loading"
    @selection-change="handleSelectionChange"
    @sort-change="handleSortChange"
    class="sales-order-table"
    :row-class-name="tableRowClassName"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="orderNumber" label="订单编号" min-width="180" show-overflow-tooltip>
      <template #default="{ row }">
        <div class="order-number-cell">
          <el-link type="primary" @click="showOrderDetail(row)">{{ row.orderNumber }}</el-link>
          <el-tag v-if="row.isGift" size="small" type="success">赠品</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="customerName" label="客户名称" min-width="120" show-overflow-tooltip />
    <el-table-column prop="orderAmount" label="订单金额" width="120" align="right">
      <template #default="{ row }">
        <span class="order-amount">¥{{ formatCurrency(row.orderAmount) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="orderStatus" label="订单状态" width="100">
      <template #default="{ row }">
        <el-tag :type="getStatusType(row.orderStatus)">
          {{ getStatusText(row.orderStatus) }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="invoiceStatus" label="发票状态" width="100">
      <template #default="{ row }">
        <el-tag :type="getInvoiceStatusType(row.invoiceStatus)">
          {{ getInvoiceStatusText(row.invoiceStatus) }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="salesperson" label="销售人员" width="100" />
    <el-table-column prop="createTime" label="创建时间" width="160">
      <template #default="{ row }">
        {{ formatDate(row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180" fixed="right">
      <template #default="scope">
        <el-button size="small" @click="showOrderDetail(scope.row)" class="action-btn detail-btn">详情</el-button>
        <el-button size="small" @click="editSalesOrder(scope.row)" class="action-btn edit-btn">编辑</el-button>
        <el-dropdown @command="handleMoreAction" class="more-dropdown">
          <el-button size="small" class="el-dropdown-link more-btn">
            更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :command="{action: 'print', row: scope.row}">
                <el-icon><Printer /></el-icon>打印订单
              </el-dropdown-item>
              <el-dropdown-item :command="{action: 'invoice', row: scope.row}">
                <el-icon><Document /></el-icon>开具发票
              </el-dropdown-item>
              <el-dropdown-item :command="{action: 'delivery', row: scope.row}" v-if="canShip(scope.row)">
                <el-icon><Van /></el-icon>发货管理
              </el-dropdown-item>
              <el-dropdown-item :command="{action: 'cancel', row: scope.row}" divided v-if="canCancel(scope.row)">
                <el-icon><Close /></el-icon>取消订单
              </el-dropdown-item>
              <el-dropdown-item :command="{action: 'delete', row: scope.row}" divided>
                <el-icon><Delete /></el-icon>删除订单
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Printer, Document, Van, Close, Delete, ArrowDown 
} from '@element-plus/icons-vue'
import type { SalesOrder } from '@/types/order'

// 定义组件属性
interface Props {
  tableData: SalesOrder[]
  loading: boolean
}

const props = defineProps<Props>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'selection-change', selection: SalesOrder[]): void
  (e: 'sort-change', sort: { column: any, prop: string, order: string }): void
  (e: 'show-detail', order: SalesOrder): void
  (e: 'edit', order: SalesOrder): void
  (e: 'print', order: SalesOrder): void
  (e: 'invoice', order: SalesOrder): void
  (e: 'delivery', order: SalesOrder): void
  (e: 'cancel', order: SalesOrder): void
  (e: 'delete', order: SalesOrder): void
}>()

// 处理选择变化
const handleSelectionChange = (selection: SalesOrder[]) => {
  emit('selection-change', selection)
}

// 处理排序变化
const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  emit('sort-change', sort)
}

// 显示订单详情
const showOrderDetail = (order: SalesOrder) => {
  emit('show-detail', order)
}

// 编辑销售订单
const editSalesOrder = (order: SalesOrder) => {
  emit('edit', order)
}

// 处理更多操作
const handleMoreAction = (command: { action: string, row: SalesOrder }) => {
  const { action, row } = command
  switch (action) {
    case 'print':
      emit('print', row)
      break
    case 'invoice':
      emit('invoice', row)
      break
    case 'delivery':
      emit('delivery', row)
      break
    case 'cancel':
      handleCancelOrder(row)
      break
    case 'delete':
      handleDeleteOrder(row)
      break
  }
}

// 判断是否可以发货
const canShip = (order: SalesOrder) => {
  return order.orderStatus === 'paid' || order.orderStatus === 'shipped'
}

// 判断是否可以取消订单
const canCancel = (order: SalesOrder) => {
  return order.orderStatus !== 'completed' && order.orderStatus !== 'cancelled'
}

// 处理取消订单
const handleCancelOrder = (order: SalesOrder) => {
  ElMessageBox.confirm(
    `确定要取消订单 ${order.platformOrderId} 吗？此操作不可恢复。`,
    '取消订单',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    emit('cancel', order)
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理删除订单
const handleDeleteOrder = (order: SalesOrder) => {
  ElMessageBox.confirm(
    `确定要删除订单 ${order.platformOrderId} 吗？此操作不可恢复。`,
    '删除订单',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(() => {
    emit('delete', order)
  }).catch(() => {
    // 用户取消操作
  })
}

// 获取订单状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, any> = {
    pending: 'info',
    confirmed: 'primary',
    processing: 'warning',
    shipped: 'success',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待处理',
    confirmed: '已确认',
    processing: '处理中',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取发票状态类型
const getInvoiceStatusType = (status: string) => {
  const statusMap: Record<string, any> = {
    uninvoiced: 'info',
    invoiced: 'warning',
    sent: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取发票状态文本
const getInvoiceStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    uninvoiced: '未开票',
    invoiced: '已开票',
    sent: '已发送'
  }
  return statusMap[status] || '未知'
}

// 格式化金额
const formatCurrency = (amount: number) => {
  return amount?.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }) || '0.00'
}

// 格式化日期
const formatDate = (date: string) => {
  return date ? new Date(date).toLocaleString('zh-CN') : ''
}

// 表格行类名
const tableRowClassName = ({ row }: { row: SalesOrder }) => {
  if (row.hasGift) {
    return 'gift-row'
  }
  return ''
}
</script>

<style scoped lang="scss">
.sales-order-table {
  :deep(.gift-row) {
    background-color: #f0f9ff;
    
    .order-number-cell {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  
  .action-btn {
    margin-right: 6px;
  }
  
  .detail-btn {
    color: #409eff;
    border-color: #409eff;
  }
  
  .edit-btn {
    color: #67c23a;
    border-color: #67c23a;
  }
  
  .more-btn {
    color: #909399;
    border-color: #dcdfe6;
  }
  
  .order-amount {
    font-weight: 500;
    color: #303133;
  }
}
</style>